package controllers

import (
	"encoding/json"
	"strconv"
	"supershare/backend/models"
	"time"

	"github.com/beego/beego/v2/server/web"
)

// GroupBuyActivityController 团购活动控制器
type GroupBuyActivityController struct {
	web.Controller
}

// GroupBuyActivityListRequest 团购活动列表请求参数
type GroupBuyActivityListRequest struct {
	Page     int    `json:"page" form:"page"`
	PageSize int    `json:"pageSize" form:"pageSize"`
	Name     string `json:"name" form:"name"`
	StoreId  int64  `json:"store_id" form:"store_id"`
	VenueId  int64  `json:"venue_id" form:"venue_id"`
	Status   int8   `json:"status" form:"status"`
}

// GroupBuyActivityResponse 团购活动响应数据
// 这个结构体用于在返回给前端时，将ApplicableStores和ApplicableVenues从ID列表转换为名称列表
type GroupBuyActivityResponse struct {
	models.GroupBuyActivity
	ApplicableStores  []string `json:"applicable_stores"`
	ApplicableVenues  []string `json:"applicable_venues"`
	AvailableWeekdays []int    `json:"available_weekdays"`
	AvailableTimes    []struct {
		Start string `json:"start_time"`
		End   string `json:"end_time"`
	} `json:"available_times"`
}

// GroupBuyActivityCreateRequest 创建团购活动请求参数
type GroupBuyActivityCreateRequest struct {
	Name              string  `json:"name"`
	Image             string  `json:"image"`
	Description       string  `json:"description"`
	OriginalPrice     float64 `json:"original_price"`
	GroupPrice        float64 `json:"group_price"`
	StartTime         int64   `json:"start_time"`
	EndTime           int64   `json:"end_time"`
	MinMembers        int     `json:"min_members"`
	MaxMembers        int     `json:"max_members"`
	LimitPerMember    int     `json:"limit_per_member"`
	Status            int8    `json:"status"`
	SortOrder         int     `json:"sort_order"`
	DeductibleHours   float64 `json:"deductible_hours"`
	ApplicableStores  []int64 `json:"applicable_stores"`
	ApplicableVenues  []int64 `json:"applicable_venues"`
	AvailableWeekdays []int   `json:"available_weekdays"`
	AvailableTimes    []struct {
		Start string `json:"start_time"`
		End   string `json:"end_time"`
	} `json:"available_times"`
	SupportBalance bool `json:"support_balance"`
}

// GroupBuyActivityUpdateRequest 更新团购活动请求参数
type GroupBuyActivityUpdateRequest struct {
	Name              string  `json:"name"`
	Image             string  `json:"image"`
	Description       string  `json:"description"`
	OriginalPrice     float64 `json:"original_price"`
	GroupPrice        float64 `json:"group_price"`
	StartTime         int64   `json:"start_time"`
	EndTime           int64   `json:"end_time"`
	MinMembers        int     `json:"min_members"`
	MaxMembers        int     `json:"max_members"`
	LimitPerMember    int     `json:"limit_per_member"`
	Status            int8    `json:"status"`
	SortOrder         int     `json:"sort_order"`
	DeductibleHours   float64 `json:"deductible_hours"`
	ApplicableStores  []int64 `json:"applicable_stores"`
	ApplicableVenues  []int64 `json:"applicable_venues"`
	AvailableWeekdays []int   `json:"available_weekdays"`
	AvailableTimes    []struct {
		Start string `json:"start_time"`
		End   string `json:"end_time"`
	} `json:"available_times"`
	SupportBalance bool `json:"support_balance"`
}

// List 获取团购活动列表
func (c *GroupBuyActivityController) List() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取请求参数
	page, _ := strconv.Atoi(c.GetString("page"))
	if page <= 0 {
		page = 1
	}

	pageSize, _ := strconv.Atoi(c.GetString("pageSize"))
	if pageSize <= 0 || pageSize > 100 {
		pageSize = 10
	}

	name := c.GetString("name")
	storeId, _ := c.GetInt64("store_id", 0)
	venueId, _ := c.GetInt64("venue_id", 0)
	status, _ := c.GetInt8("status", -1)

	// 构建过滤条件
	filters := make(map[string]interface{})
	if name != "" {
		filters["name"] = name
	}
	if storeId > 0 {
		filters["store_id"] = storeId
	}
	if venueId > 0 {
		filters["venue_id"] = venueId
	}
	if status >= 0 {
		filters["status"] = status
	}

	// 加盟商权限过滤
	if permResult.Admin.FranchiseId > 0 {
		filters["franchise_id"] = permResult.Admin.FranchiseId
	}

	// 获取团购活动列表
	activities, total, err := models.GetGroupBuyActivityList(page, pageSize, filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取团购活动列表失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 创建响应列表
	responseList := make([]GroupBuyActivityResponse, len(activities))
	for i, activity := range activities {
		var storeIDs []int64
		json.Unmarshal([]byte(activity.ApplicableStores), &storeIDs)

		var venueIDs []int64
		json.Unmarshal([]byte(activity.ApplicableVenues), &venueIDs)

		var availableWeekdays []int
		json.Unmarshal([]byte(activity.AvailableWeekdays), &availableWeekdays)

		availableTimes := []struct {
			Start string `json:"start_time"`
			End   string `json:"end_time"`
		}{}
		json.Unmarshal([]byte(activity.AvailableTimes), &availableTimes)

		storeNames := []string{}
		if len(storeIDs) > 0 {
			stores, err := models.GetStoresByIds(storeIDs)
			if err == nil {
				for _, s := range stores {
					storeNames = append(storeNames, s.Name)
				}
			}
		}

		venueNames := []string{}
		if len(venueIDs) > 0 {
			venues, err := models.GetVenuesByIds(venueIDs)
			if err == nil {
				for _, v := range venues {
					venueNames = append(venueNames, v.Name)
				}
			}
		}

		responseList[i] = GroupBuyActivityResponse{
			GroupBuyActivity:  *activity,
			ApplicableStores:  storeNames,
			ApplicableVenues:  venueNames,
			AvailableWeekdays: availableWeekdays,
			AvailableTimes:    availableTimes,
		}
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"data": map[string]interface{}{
			"list":  responseList,
			"total": total,
		},
	}
	c.ServeJSON()
}

// GetOne 获取团购活动详情
func (c *GroupBuyActivityController) GetOne() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取活动ID
	idStr := c.Ctx.Input.Param(":id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil || id <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的活动ID",
		}
		c.ServeJSON()
		return
	}

	// 获取活动详情
	activity, err := models.GetGroupBuyActivityById(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取团购活动详情失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	hasAccess, _ := models.CheckGroupBuyActivityAccess(id, permResult.Admin.FranchiseId)
	if !hasAccess {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权访问此团购活动",
		}
		c.ServeJSON()
		return
	}

	// 创建响应对象并反序列化
	var storeIDs []int64
	json.Unmarshal([]byte(activity.ApplicableStores), &storeIDs)

	var venueIDs []int64
	json.Unmarshal([]byte(activity.ApplicableVenues), &venueIDs)

	var availableWeekdays []int
	json.Unmarshal([]byte(activity.AvailableWeekdays), &availableWeekdays)

	availableTimes := []struct {
		Start string `json:"start_time"`
		End   string `json:"end_time"`
	}{}
	json.Unmarshal([]byte(activity.AvailableTimes), &availableTimes)

	storeNames := []string{}
	if len(storeIDs) > 0 {
		stores, err := models.GetStoresByIds(storeIDs)
		if err == nil {
			for _, s := range stores {
				storeNames = append(storeNames, s.Name)
			}
		}
	}

	venueNames := []string{}
	if len(venueIDs) > 0 {
		venues, err := models.GetVenuesByIds(venueIDs)
		if err == nil {
			for _, v := range venues {
				venueNames = append(venueNames, v.Name)
			}
		}
	}

	response := GroupBuyActivityResponse{
		GroupBuyActivity:  *activity,
		ApplicableStores:  storeNames,
		ApplicableVenues:  venueNames,
		AvailableWeekdays: availableWeekdays,
		AvailableTimes:    availableTimes,
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取团购活动详情成功",
		"data":    response,
	}
	c.ServeJSON()
}

// Create 创建团购活动
func (c *GroupBuyActivityController) Create() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析请求数据
	var req GroupBuyActivityCreateRequest
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求数据",
		}
		c.ServeJSON()
		return
	}

	// 验证必填字段
	if req.Name == "" {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "活动名称不能为空",
		}
		c.ServeJSON()
		return
	}

	if req.OriginalPrice <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "原价必须大于0",
		}
		c.ServeJSON()
		return
	}

	if req.GroupPrice <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "团购价必须大于0",
		}
		c.ServeJSON()
		return
	}

	if req.GroupPrice >= req.OriginalPrice {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "团购价必须低于原价",
		}
		c.ServeJSON()
		return
	}

	if req.StartTime <= 0 || req.EndTime <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "活动时间不能为空",
		}
		c.ServeJSON()
		return
	}

	if req.StartTime >= req.EndTime {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "结束时间必须晚于开始时间",
		}
		c.ServeJSON()
		return
	}

	if req.MinMembers < 2 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "最少参团人数不能小于2",
		}
		c.ServeJSON()
		return
	}

	if req.MaxMembers > 0 && req.MaxMembers < req.MinMembers {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "最大参团人数不能小于最少参团人数",
		}
		c.ServeJSON()
		return
	}

	// 序列化 applicable_stores 和 applicable_venues
	storesBytes, err := json.Marshal(req.ApplicableStores)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "序列化可用门店失败",
		}
		c.ServeJSON()
		return
	}

	venuesBytes, err := json.Marshal(req.ApplicableVenues)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "序列化可用场地失败",
		}
		c.ServeJSON()
		return
	}

	weekdaysBytes, err := json.Marshal(req.AvailableWeekdays)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "序列化可用星期失败",
		}
		c.ServeJSON()
		return
	}

	timesBytes, err := json.Marshal(req.AvailableTimes)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "序列化可用时段失败",
		}
		c.ServeJSON()
		return
	}

	// 创建团购活动对象
	activity := &models.GroupBuyActivity{
		Name:              req.Name,
		Image:             req.Image,
		Description:       req.Description,
		OriginalPrice:     req.OriginalPrice,
		GroupPrice:        req.GroupPrice,
		StartTime:         req.StartTime,
		EndTime:           req.EndTime,
		MinMembers:        req.MinMembers,
		MaxMembers:        req.MaxMembers,
		LimitPerMember:    req.LimitPerMember,
		Status:            req.Status,
		SortOrder:         req.SortOrder,
		DeductibleHours:   req.DeductibleHours,
		ApplicableStores:  string(storesBytes),
		ApplicableVenues:  string(venuesBytes),
		AvailableWeekdays: string(weekdaysBytes),
		AvailableTimes:    string(timesBytes),
		SupportBalance:    req.SupportBalance,
		BaseModel: models.BaseModel{
			FranchiseId: permResult.Admin.FranchiseId,
		},
	}

	// 设置创建者信息
	activity.CreatedBy = permResult.Admin.Username
	activity.CreatedAt = time.Now().Unix()
	activity.UpdatedBy = permResult.Admin.Username
	activity.BeforeInsert()

	// 创建团购活动
	id, err := models.CreateGroupBuyActivity(activity)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "创建团购活动失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "创建团购活动成功",
		"data": map[string]interface{}{
			"id": id,
		},
	}
	c.ServeJSON()
}

// Update 更新团购活动
func (c *GroupBuyActivityController) Update() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取活动ID
	idStr := c.Ctx.Input.Param(":id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil || id <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的活动ID",
		}
		c.ServeJSON()
		return
	}

	// 获取活动详情
	activity, err := models.GetGroupBuyActivityById(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取团购活动详情失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if permResult.Admin.FranchiseId > 0 && activity.FranchiseId != permResult.Admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权更新此团购活动",
		}
		c.ServeJSON()
		return
	}

	// 解析请求数据
	var req GroupBuyActivityUpdateRequest
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求数据" + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 验证必填字段
	if req.Name == "" {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "活动名称不能为空",
		}
		c.ServeJSON()
		return
	}

	if req.OriginalPrice <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "原价必须大于0",
		}
		c.ServeJSON()
		return
	}

	if req.GroupPrice <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "团购价必须大于0",
		}
		c.ServeJSON()
		return
	}

	if req.GroupPrice >= req.OriginalPrice {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "团购价必须低于原价",
		}
		c.ServeJSON()
		return
	}

	if req.StartTime <= 0 || req.EndTime <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "活动时间不能为空",
		}
		c.ServeJSON()
		return
	}

	if req.StartTime >= req.EndTime {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "结束时间必须晚于开始时间",
		}
		c.ServeJSON()
		return
	}

	if req.MinMembers < 2 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "最少参团人数不能小于2",
		}
		c.ServeJSON()
		return
	}

	if req.MaxMembers > 0 && req.MaxMembers < req.MinMembers {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "最大参团人数不能小于最少参团人数",
		}
		c.ServeJSON()
		return
	}

	// 序列化 applicable_stores 和 applicable_venues
	storesBytes, err := json.Marshal(req.ApplicableStores)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "序列化可用门店失败",
		}
		c.ServeJSON()
		return
	}

	venuesBytes, err := json.Marshal(req.ApplicableVenues)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "序列化可用场地失败",
		}
		c.ServeJSON()
		return
	}

	weekdaysBytes, err := json.Marshal(req.AvailableWeekdays)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "序列化可用星期失败",
		}
		c.ServeJSON()
		return
	}

	timesBytes, err := json.Marshal(req.AvailableTimes)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "序列化可用时段失败",
		}
		c.ServeJSON()
		return
	}

	// 更新活动数据
	activity.Name = req.Name
	activity.Image = req.Image
	activity.Description = req.Description
	activity.OriginalPrice = req.OriginalPrice
	activity.GroupPrice = req.GroupPrice
	activity.StartTime = req.StartTime
	activity.EndTime = req.EndTime
	activity.MinMembers = req.MinMembers
	activity.MaxMembers = req.MaxMembers
	activity.LimitPerMember = req.LimitPerMember
	activity.Status = req.Status
	activity.SortOrder = req.SortOrder
	activity.DeductibleHours = req.DeductibleHours
	activity.ApplicableStores = string(storesBytes)
	activity.ApplicableVenues = string(venuesBytes)
	activity.AvailableWeekdays = string(weekdaysBytes)
	activity.AvailableTimes = string(timesBytes)
	activity.SupportBalance = req.SupportBalance
	activity.UpdatedBy = permResult.Admin.Username
	activity.BeforeUpdate()

	// 更新团购活动
	err = models.UpdateGroupBuyActivity(activity)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "更新团购活动失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "更新团购活动成功",
	}
	c.ServeJSON()
}

// Delete 删除团购活动
func (c *GroupBuyActivityController) Delete() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取活动ID
	idStr := c.Ctx.Input.Param(":id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil || id <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的活动ID",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	hasAccess, _ := models.CheckGroupBuyActivityAccess(id, permResult.Admin.FranchiseId)
	if !hasAccess {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权删除此团购活动",
		}
		c.ServeJSON()
		return
	}

	// 删除活动
	err = models.DeleteGroupBuyActivity(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "删除团购活动失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "删除团购活动成功",
	}
	c.ServeJSON()
}

// GetActiveActivities 获取当前有效的团购活动列表（小程序端）
func (c *GroupBuyActivityController) GetActiveActivities() {
	// 获取请求参数
	storeIdStr := c.GetString("store_id")
	storeId, _ := strconv.ParseInt(storeIdStr, 10, 64)

	// 设置加盟商ID为0，允许游客访问
	franchiseId := int64(0)

	// 获取活动列表
	activities, err := models.GetActiveGroupBuyActivities(storeId, franchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取团购活动列表失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取团购活动列表成功",
		"data":    activities,
	}
	c.ServeJSON()
}

// GetActive 获取当前有效的团购活动（管理端）
func (c *GroupBuyActivityController) GetActive() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取请求参数
	storeIdStr := c.GetString("store_id")
	storeId, _ := strconv.ParseInt(storeIdStr, 10, 64)

	// 获取活动列表
	activities, err := models.GetActiveGroupBuyActivities(storeId, permResult.Admin.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取团购活动列表失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取团购活动列表成功",
		"data":    activities,
	}
	c.ServeJSON()
}
